package com.cn.fangshuo.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cn.fangshuo.entity.CarWash;
import com.cn.fangshuo.entity.CarWashPushLog;
import com.cn.fangshuo.enums.RedisKeyEnum;
import com.cn.fangshuo.service.ICarWashPushLogService;
import com.cn.fangshuo.service.ICarWashService;
import com.cn.fangshuo.util.RedisUtil;
import com.cn.fangshuo.util.StrUtil;
import com.cn.fangshuo.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
public class PushShenYangCarWashTask {

    private static final Logger logger = LoggerFactory.getLogger(PushShenYangCarWashTask.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICarWashService carWashService;

    @Autowired
    private ICarWashPushLogService carWashPushLogService;

    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void push() {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime;

        String lastCarWashPushTime = redisUtil.getString(RedisKeyEnum.LAST_CAR_WASH_PUSH_TIME.getKey() + "YYCC1000001287");
        if (StrUtil.isBlank(lastCarWashPushTime)){
            startTime = LocalDateTime.now().minusMinutes(5);
        } else {
            startTime = TimeUtil.parseLocalDateTime(lastCarWashPushTime);
        }
        List<CarWash> list = carWashService.list(new LambdaQueryWrapper<CarWash>().ge(CarWash::getCreateTime, startTime).lt(CarWash::getCreateTime, endTime).eq(CarWash::getDeviceUuid, "YYCC1000001287"));
        if (CollUtil.isNotEmpty( list)){
            logger.info("==========推送沈阳车冲信息开始：{}====================", TimeUtil.format(endTime));
            list.parallelStream().forEach(carWash -> {
                JSONObject pushInfo = new JSONObject();
                pushInfo.put("deviceCode", carWash.getDeviceUuid());
                pushInfo.put("licensePlateNumber", carWash.getLicensePlateNum());
                pushInfo.put("washState", carWash.getEvent() > 2 ? 2 : 0);
                pushInfo.put("startTime", carWash.getWashTime());
                pushInfo.put("endTime", TimeUtil.format(TimeUtil.parseLocalDateTime(carWash.getWashTime()).plusSeconds(carWash.getWashTotalDuration())));
                pushInfo.put("imageUrl", carWash.getImages().split(",")[0]);
                pushInfo.put("recordTime", TimeUtil.format(carWash.getCreateTime()));
                logger.info(pushInfo.toJSONString());

                //推送日志
                CarWashPushLog log = new CarWashPushLog();
                log.setDeviceUuid(carWash.getDeviceUuid());
                log.setCarWashTime(TimeUtil.parseLocalDateTime(carWash.getWashTime()));
                log.setParams(pushInfo.toJSONString());
                log.setCreateTime(LocalDateTime.now());
                try (HttpResponse response = HttpRequest.post("https://erp.huizhuyun.com/api/huizhuyun-hardware-collector/construction-platform/wash/real-time-data")
                        .header("Content-Type", "application/json") // 明确设置JSON类型
                        .body(pushInfo.toJSONString())  // 传入JSON字符串
                        .execute()) {
                    logger.info(response.body());
                    log.setSuccess(response.isOk());
                    log.setReponse(response.body());
                    carWashPushLogService.save(log);
                }
            });
            logger.info("==========推送沈阳车冲信息结束：{}====================", TimeUtil.format(endTime));
        }
        redisUtil.set(RedisKeyEnum.LAST_CAR_WASH_PUSH_TIME.getKey() + "YYCC1000001287", TimeUtil.format(endTime));
   }
}
